import gulp from "gulp";
import gulpLoadPlugins from "gulp-load-plugins";
import browserSync from "browser-sync";
import ngAnnotate from "gulp-ng-annotate";
import gulpif from "gulp-if";
import useref from "gulp-useref";
import { createProxyMiddleware } from "http-proxy-middleware";
import replace from "gulp-replace";

const bs = browserSync.create();

const $ = gulpLoadPlugins();
// var $ = require("gulp-load-plugins")();

const ASSSET = {
  cssdir: "app/styles",
  cssfile: "app/styles/*.css",
  viewsfile: "app/views/**/*.html",
  jsfile: "app/scripts/**/*.js",
  indexStyl: "app/stylus/index.styl",
  stylusfile: "app/stylus/*.styl",
};
const APP = "app";

gulp.task("html", function () {
  const timestamp = new Date().getTime();
  // 关于useref用法可以访问以下路径查看
  //https://www.npmjs.com/package/gulp-useref
  return (
    gulp
      .src("app/*.html")
      .pipe(gulpif("*.css", $.csso())) //css压缩-->合并
      .pipe(gulpif("*.js", ngAnnotate())) //angular压缩时候，要显示声明依赖不然会报错
      // .pipe(gulpif('*.js', $.uglify()))
      .pipe(useref())
      // .pipe(replace(/(\.css|\.js)/g, `$1?v=${timestamp}`)) // 替换文件路径添加时间戳
      .pipe(
        replace(
          /(<link.*?href=["'].*?)(\.css)(["'].*?>)/g,
          `$1$2?v=${timestamp}$3`
        )
      ) // 替换 link 中的 .css
      .pipe(
        replace(
          /(<script.*?src=["'].*?)(\.js)(["'].*?>)/g,
          `$1$2?v=${timestamp}$3`
        )
      ) // 替换 script 中的 .js
      .pipe(gulp.dest("www"))
  );
});
gulp.task("views", function () {
  return gulp
    .src(ASSSET.viewsfile)
    .pipe(
      gulpif(
        "*.html",
        $.minifyHtml({
          conditionals: true,
          loose: true,
        })
      )
    )
    .pipe(gulp.dest("www/views"));
});
gulp.task("images", function () {
  return (
    gulp
      .src("app/images/*")
      // .pipe($.imagemin())
      .pipe(gulp.dest("www/images"))
  );
});

gulp.task("static", ["images"], function () {});

gulp.task("extras", function () {
  return gulp
    .src(["app/*.*", "!app/*.html"], {
      dot: true,
    })
    .pipe(gulp.dest("www"));
});

gulp.task("clean", require("del").bind(null, ["www"]));

gulp.task("wiredep", function () {
  var wiredep = require("wiredep").stream;
  gulp
    .src("app/*.html")
    .pipe(
      wiredep({
        ignorePath: /^(\.\.\/)*\.\./,
      })
    ) //{ignorePath: /^(\.\.\/)*\.\./}
    .pipe(gulp.dest("app"));
});

// 编译-->合并（该任务是开发时候用的）
gulp.task("styles", ["stylus", "concatCss"], function () {});
gulp.task("concatCss", function () {
  return gulp
    .src("app/vendor/*.css")
    .pipe($.concatCss("vendor.css"))
    .pipe(gulp.dest(ASSSET.cssdir));
});
gulp.task("stylus", function () {
  gulp
    .src(ASSSET.indexStyl)
    .pipe($.sourcemaps.init())
    .pipe($.stylus())
    .pipe($.sourcemaps.write("."))
    .pipe(gulp.dest(ASSSET.cssdir));
});
// 该任务是开发时候用的end

gulp.task("default", ["clean"], function () {
  gulp.start("build");
});
gulp.task("watch", function () {
  gulp.watch(ASSSET.stylusfile, ["stylus"]);
});

/**
 * Configure proxy middleware
 */
var jsonPlaceholderProxy = createProxyMiddleware("/proxy/", {
  target: "http://oa.jianguanoa.com/",
  // target: 'http://192.168.0.3:8019/',

  changeOrigin: true, // for vhosted sites, changes host header to match to target's host
  pathRewrite: {
    "^/proxy/": "",
  },
  logLevel: "debug",
  onProxyReq: (proxyReq, req, res) => {
    // console.log(res);
  },
});

gulp.task("serve", ["clean", "stylus"], function () {
  bs.init({
    files: [APP + "/**/*.html", ASSSET.cssfile, ASSSET.jsfile],
    notify: false,
    port: 9000,
    server: [".", APP], //这里读取当前目录或者app目录
    middleware: [jsonPlaceholderProxy],
  });

  gulp.watch(ASSSET.stylusfile, ["stylus"]);
  gulp.watch("bower.json", ["wiredep"]);
});
gulp.task("build", ["html", "static", "views", "extras"], function () {
  return gulp
    .src("www/**/*")
    .pipe(
      $.size({
        title: "build",
        gzip: true,
      })
    )
    .pipe(gulp.dest("www"));
});
